package com.wangyang.stock.web.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.wangyang.stock.po.Operator;
import com.wangyang.stock.po.Permission;

public class FangwenFilter implements Filter {

	public void destroy() {
	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		String uri = req.getRequestURI();

		HttpSession session = req.getSession();
		Operator opr = (Operator) session.getAttribute("employee");
		if (null != opr) {
			Set<Permission> perSet = opr.getRole().getPermissions();

			List<String> pathList = new ArrayList<String>();
			Iterator<Permission> it = perSet.iterator();
			while (it.hasNext()) {
				Permission per = it.next();
				pathList.add(per.getPermissionNews());
			}

			boolean is = false;
			if (-1 != uri.indexOf("/pages/PaladinStock")) {
				is = true;
			} else {
				for (int i = 0; i < pathList.size(); i++) {
					if (-1 != uri.indexOf(pathList.get(i))) {
						is = true;
						break;
					}
				}
			}
			if (is) {
				chain.doFilter(request, response);
			} else {
				rep.sendRedirect("/stock/login.jsp");
			}
		} else {
			rep.sendRedirect("/stock/login.jsp");
		}

	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}
}
